package cn.tqfeiyang.springplus.framework.logging;

import cn.tqfeiyang.springplus.framework.Constants;
import cn.tqfeiyang.springplus.framework.toolkit.NetworkUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 客户端IP过滤器。
 *
 * 每次请求时，将客户端的IP地址注入到 MDC（Mapped Diagnostic Context） 中，这样可以在日志中显示。
 *
 * @author tqfeiyang
 * @since 2024-07-19
 */
@Component
public class ClientAddressFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        MDC.put(Constants.MDC_CLIENT_IP, NetworkUtils.getRequestIp(request));
        filterChain.doFilter(request, response);
    }

}
